package com.dtu.snapdroid;

import java.io.File;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.dtu.ImagesExtras.ImageAndText;
import com.dtu.ImagesExtras.ImageGalleryAdapter;
import com.dtu.XMLExtras.ReadXML;
import com.dtu.XMLExtras.ReadXMLImages;
import com.dtu.XMLExtras.Uploader;
import com.dtu.XMLExtras.WriteXMLLocation;
import com.dtu.XMLExtras.WriteXMLPhotoInfo;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.BaseRequestListener;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.LoginButton;
import com.facebook.android.SessionEvents;
import com.facebook.android.SessionEvents.AuthListener;
import com.facebook.android.SessionEvents.LogoutListener;
import com.facebook.android.SessionStore;
import com.facebook.android.Util;

public class SnapMain extends Activity {

	public static String tagApplierResult;
	public static ReadXML readXML;
	private final int CAMERA_ACTIVITY = 1;
	public static String userName;

	/*Facebook Login*/
	public static final String APP_ID = "135034016567364";
	private LoginButton mLoginButton;
	private Facebook mFacebook;
	private AsyncFacebookRunner mAsyncRunner;
	private Uploader upl;
	private TextView headName;
	
	private String userID;

	private ArrayAdapter<String> statusListAdapter ;

	private Button snapButton;
	private Gallery mGallery;
	private ListView listStatus;

	private String imagePath;
	private ArrayList<ImageAndText> imageList;

	ArrayList<String> descriptionTexts;

	
	LocationProvider mLocationProvider;
	ReadXMLImages mImageDownloadHandler;

	////////////////////////////////////////////////////////////

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.snapmain);
		
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		upl = new Uploader();

		readXML = new ReadXML();
		mLocationProvider = new LocationProvider(this);
		mImageDownloadHandler = new ReadXMLImages();
		headName = (TextView) findViewById(R.id.loginname);
		userName = "";

		/*Facebook Login*/
		mFacebook = new Facebook(APP_ID);
		mAsyncRunner = new AsyncFacebookRunner(mFacebook);
		SessionStore.restore(mFacebook, this);
		SessionEvents.addAuthListener(new SampleAuthListener());
		mLoginButton = (LoginButton) findViewById(R.id.login);
		mLoginButton.init(this, mFacebook);

		mAsyncRunner.request("me", new SampleRequestListener());
		
		
		
	
		
		
		mImageDownloadHandler.setPath("http://loftur.com/Pics/results.xml");
		
		imageList = mImageDownloadHandler.getImages();	
		mGallery = (Gallery) findViewById(R.id.gallery);
		mGallery.setAdapter(new ImageGalleryAdapter(this,this,imageList, mGallery));
		mGallery.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
				updateAll();
				new PictureInflater(SnapMain.this, imageList.get(position).getImageUrl(), 1, imageList.get(position).getText()).show()	;
			}
		});
		
		readXML.setTag("Image");
		readXML.setAttr("Description");
		readXML.setPath("http://loftur.com/Pics/results.xml");
		descriptionTexts = readXML.getInfo();
		statusListAdapter = new ArrayAdapter<String>(this, R.layout.listitem, descriptionTexts);
		listStatus = (ListView) findViewById(R.id.listinfo);		
		listStatus.setAdapter(statusListAdapter);
		listStatus.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
				
				mGallery.setSelection(position,false);
			}
		});

		snapButton = ( Button ) findViewById( R.id.snapbutton);
		snapButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v){
				
				if(userName.equals(""))
					Toast.makeText(getApplicationContext(), "Please login....", Toast.LENGTH_SHORT).show();

				else if (mLocationProvider.getLatitude() == 0 && mLocationProvider.getLongitude() == 0)	
					Toast.makeText(getApplicationContext(), "Location not aquired. Try again.", Toast.LENGTH_SHORT).show();
				
				else{
					imagePath = Environment.getExternalStorageDirectory()+"/temp.jpg";

					WriteXMLLocation wxml = new WriteXMLLocation();

					//Get coordinates
					double latitude = mLocationProvider.getLatitude(); //55.756454
					double longitude = mLocationProvider.getLongitude(); // 12.472314

					//CreateXML file with coordinates
					wxml.createXMLfile(latitude, longitude);
					upl.send(Environment.getExternalStorageDirectory()+"/location.xml", "http://www.loftur.com/locations/uploadLocation.php");

					File file = new File(imagePath);
					Uri outputFileUri = Uri.fromFile( file );

					Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
					intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );

					startActivityForResult(intent,CAMERA_ACTIVITY);
				}		
			}			
		});
		////////////////////////////////////////////////////////////
	}

	private void updateAll(){
		// Update status list
		
		statusListAdapter.clear();
		readXML.setTag("Image");
		readXML.setAttr("Description");
		readXML.setPath("http://loftur.com/Pics/results.xml");
		descriptionTexts = readXML.getInfo();
		
		for (String s : descriptionTexts)
			statusListAdapter.add(s);

		statusListAdapter.notifyDataSetChanged();
		
		imageList = mImageDownloadHandler.getImages();
		mGallery.setAdapter(new ImageGalleryAdapter(this,this,imageList, mGallery));
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if(resultCode==RESULT_OK){
			Log.e( "Snapdroid", "requestCode: " + requestCode );
			switch( requestCode )
			{
			case CAMERA_ACTIVITY:
				// Photo taken
				upl.send(imagePath, "http://www.loftur.com/Pics/upload.php");

				WriteXMLPhotoInfo wxmlPhotoInfo = new WriteXMLPhotoInfo();

				//CreateXML file with coordinate
				wxmlPhotoInfo.createXMLfile(userName, tagApplierResult);
				upl.send(Environment.getExternalStorageDirectory()+"/photoinfo.xml", "http://www.loftur.com/Pics/uploadPicInfo.php");

				

				readXML.setTag("Location");
				readXML.setAttr("Location");
				readXML.setPath("http://www.loftur.com/locations/tags.xml");
				
				TagApplier ta = new TagApplier(SnapMain.this, readXML.getInfo());
				ta.setOnDismissListener(new DialogInterface.OnDismissListener(){
					public void onDismiss(DialogInterface dialog) {						
						updateAll();
					}
				});
				ta.show();
				
				break;


			default:
				break;
			}
		}
		else{
			Toast.makeText(getApplicationContext(), "Activity cancelled", Toast.LENGTH_SHORT).show();
		}
	}

	public class SampleRequestListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			try {
				// process the response here: executed in background thread
				Log.d("Facebook-Example", "Response: " + response.toString());
				JSONObject json = Util.parseJson(response);
				userName = json.getString("first_name");
				userID = json.getString("id");

				// then post the processed result back to the UI thread
				// if we do not do this, an runtime exception will be generated
				// e.g. "CalledFromWrongThreadException: Only the original
				// thread that created a view hierarchy can touch its views."
				SnapMain.this.runOnUiThread(new Runnable() {
					public void run() {
						headName.setText(userName);

					}
				});
			} catch (JSONException e) {
				Log.w("Facebook-Example", "JSON Error in response");
			} catch (FacebookError e) {
				Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
			}
		}
	}

	public class SampleLogoutListener implements LogoutListener {
		public void onLogoutBegin() {
			headName.setText("");			
		}

		public void onLogoutFinish() {
			Toast.makeText(getApplicationContext(), "Logged out.", Toast.LENGTH_SHORT).show();
			headName.setText("");

		}
	}

	public class SampleAuthListener implements AuthListener {

		public void onAuthSucceed() {
			Toast.makeText(getApplicationContext(), "Logged in!", Toast.LENGTH_SHORT).show();
			mAsyncRunner.request("me", new SampleRequestListener());
		}

		public void onAuthFail(String error) {
			Toast.makeText(getApplicationContext(), "Login failed...", Toast.LENGTH_SHORT).show();
			headName.setText("");
		}
	}

	public class SampleUploadListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			try {
				// process the response here: (executed in background thread)
				Log.d("Facebook-Example", "Response: " + response.toString());
				JSONObject json = Util.parseJson(response);
				userName = json.getString("name");
				final String src = json.getString("src");

				// then post the processed result back to the UI thread
				// if we do not do this, an runtime exception will be generated
				// e.g. "CalledFromWrongThreadException: Only the original
				// thread that created a view hierarchy can touch its views."

			} catch (JSONException e) {
				Log.w("Facebook-Example", "JSON Error in response");
			} catch (FacebookError e) {
				Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
			}
		}
	}

}